package com.manor.main.fragment

import android.content.Intent
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.manor.common.CommonAppConfig
import com.manor.common.HtmlConfig
import com.manor.common.activity.WebViewActivity
import com.manor.common.constant.UserInfoUtil
import com.manor.common.event.LocationEvent
import com.manor.common.fragment.BaseFragment
import com.manor.common.http.HttpCallback
import com.manor.common.ktx.toBeanList
import com.manor.common.utils.*
import com.manor.main.BuildConfig
import com.manor.main.R
import com.manor.main.activity.LybCheckNewsActivity
import com.manor.main.activity.MainActivity
import com.manor.main.activity.MainSearchActivity
import com.manor.main.activity.UserCenterActivity
import com.manor.main.adapter.MainBottomSameCityAdapter
import com.manor.main.bean.BottomSameCityBean
import com.manor.main.bean.HomeBannerBean
import com.manor.main.http.MainHttpUtil
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.adapter.BannerAdapter
import com.youth.banner.indicator.CircleIndicator
import com.youth.banner.util.BannerUtils
import kotlinx.android.synthetic.main.fragment_home.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 *
 * @date  2021/3/26  13:58
 * @version 1.0
 */
class HomeFragment : BaseFragment(), View.OnClickListener {

    private var pageNum = 1
    private var lastId = ""
    private var mCityAdapter: MainBottomSameCityAdapter? = null
    private var dataList = mutableListOf<BottomSameCityBean>()
    private var bannerList: MutableList<HomeBannerBean> = mutableListOf()

    companion object {
        fun newInstance(): HomeFragment {
            return HomeFragment()
        }
    }

    override fun getLayoutRes(): Int = R.layout.fragment_home

    override fun initView() {
        llSearch.setOnClickListener(this)
        tvManor.setOnClickListener(this)
        tvMarket.setOnClickListener(this)
        tvGuide.setOnClickListener(this)
        tvLocal.setOnClickListener(this)
        tvVerify.setOnClickListener(this)
        initRecycler()
        loadDate()
        //loadBanner()
        mBanner?.addBannerLifecycleObserver(this)

        EventBus.getDefault().register(this)
        tvLocal?.text = """${CommonAppConfig.getInstance()?.city ?: ""}${CommonAppConfig.getInstance()?.district ?: ""}"""
    }

    override fun onResume() {
        super.onResume()
        if (UserInfoUtil.getPhone() == "13914800206"){
            mCheckBannerIv.v(true)
            mBanner.v(false)
            tvManor.text = "淘米生活圈"
            tvVerify.v(false)
        }else{
            loadBanner()
        }

    }

    override fun onStop() {
        super.onStop()
        LocationUtil.getInstance().stopLocation()
    }

    override fun onDestroyView() {
        EventBus.getDefault().unregister(this)
        super.onDestroyView()
    }


    private fun initBanner() {
        mBanner?.run {
            //this.addBannerLifecycleObserver(this@HomeFragment)
            this.adapter = BannerImgAdapter(bannerList)
            this.indicator = CircleIndicator(activity)
            this.adapter.setOnBannerListener { data, position ->
                if (bannerList[position].url.notNull()) {
                    WebViewActivity.forwars(activity, bannerList[position].url)
                } else {
                    // WebViewActivity.forwars(activity, "https://www.baidu.com/")
                }

            }
//            this.setBannerGalleryEffect(20, 10)
        }


    }

    private fun initRecycler() {
        mRecycleView.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        mCityAdapter = MainBottomSameCityAdapter(R.layout.rv_mainsamecity_item, dataList)
        mRecycleView.adapter = mCityAdapter
        mCityAdapter?.setOnItemClickListener { adapter, view, position ->
            if (position >= dataList.size)
                return@setOnItemClickListener
            if (dataList[position].isgg == "CPM") {
                if (!dataList[position].jump_url.isNullOrEmpty()) {
                    WebViewActivity.forwars(activity, dataList[position].jump_url)
                }
            } else if (!dataList[position].id.isNullOrEmpty()) {
                activity?.let { UserCenterActivity.forward(it, dataList[position].id) }
            }
        }
        refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageNum = 1
                loadDate()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                pageNum++
                loadDate()
            }
        })

    }

    private fun initLocal() {
        LocationUtil.getInstance().startLocation {

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLocalSuc(event: LocationEvent) {
        tvLocal?.text = """${CommonAppConfig.getInstance()?.city ?: ""}${CommonAppConfig.getInstance()?.district ?: ""}"""
    }


    private fun loadDate() {
        lastId = if (StringUtil.isListNotEmpty(dataList)) {
            dataList.last().id
        } else {
            ""
        }
        MainHttpUtil.getNear(pageNum, "", "", "", "", lastId, object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String?, info: String?) {
                if (code == 0) {
                    refreshLayout.finishRefresh()
                    refreshLayout.finishLoadMore()
                    if (StringUtil.isNotEmpty(info)) {
                        info?.run {
                            val bean = this.toBeanList<BottomSameCityBean>()
                            if (pageNum == 1) {
                                dataList.clear()
                            }
                            dataList.addAll(bean)

                            if (dataList.isNullOrEmpty()) {
                                mCityAdapter?.setEmptyView(R.layout.view_empty_default)
                            }

                            mCityAdapter?.notifyDataSetChanged()
                        }
                    }
                }
            }

            override fun onError() {
                super.onError()
                refreshLayout.finishRefresh()
                refreshLayout.finishLoadMore()
                if (pageNum > 1) {
                    pageNum--
                }
                if (dataList.isNullOrEmpty()) {
                    mCityAdapter?.setEmptyView(R.layout.view_empty_default)
                }
            }

        })

    }

    private fun loadBanner() {
        MainHttpUtil.getBanner(object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String?, info: String?) {
                if (code == 0) {
                    if (StringUtil.isNotEmpty(info)) {
                        info?.run {
                            val bean = this.toBeanList<HomeBannerBean>()
                            bannerList.clear()
                            bannerList.addAll(bean)
                            initBanner()

                        }
                    }
                }
            }
            override fun onError() {
                super.onError()
            }
        })
    }

    override fun onClick(v: View?) {
        if (ClickUtil.canClick()) {
            when (v?.id) {
                R.id.llSearch -> {
                    MainSearchActivity.forward(context)
                }
                R.id.tvManor -> {
                    if (BuildConfig.DEBUG){
                        RouteUtil.startActivityFairyParkActivityNewLyb()
                    }else{
                        if (UserInfoUtil.getPhone() == "13914800206"){
                            (activity as MainActivity).setToThridPart()
                        }else{
                            RouteUtil.startActivityFairyParkActivityNewLyb()
                        }
                    }
                }
                R.id.tvMarket -> {
                    if (BuildConfig.DEBUG){
                        RouteUtil.forwardElvesHome()
                    }else{
                        ToastUtils.make().setGravity(Gravity.CENTER,0,0).show("暂未开放")
                    }
                }
                R.id.tvGuide -> {
                    //新手指南
                    if (UserInfoUtil.getPhone() == "13914800206"){
                        startActivity(Intent(activity, LybCheckNewsActivity::class.java))
                    }else{
                        WebViewActivity.forwars(activity, HtmlConfig.LINK_NEWER_GUIDE)
                    }
                }
                R.id.tvVerify -> {
                    ToastUtils.make()
                            .setGravity(Gravity.CENTER,0,0)
                            .show("暂未开放")
                }
                R.id.tvLocal -> {

                }
            }
        }
    }

    private class BannerImgAdapter(imageUrls: List<HomeBannerBean>)
        : BannerAdapter<HomeBannerBean, BannerImgAdapter.ImageHolder>(imageUrls) {


        override fun onCreateHolder(parent: ViewGroup?, viewType: Int): ImageHolder {
            val imageView = ImageView(parent!!.context)
            val params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
            imageView.layoutParams = params
            imageView.scaleType = ImageView.ScaleType.CENTER_CROP
            //通过裁剪实现圆角
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                BannerUtils.setBannerRound(imageView, 20f)
            }
            return ImageHolder(imageView)
        }

        override fun onBindView(holder: ImageHolder?, data: HomeBannerBean?, position: Int, size: Int) {
            if (holder != null) {
                if (data != null) {
                    Glide.with(holder.itemView).load(data.image)
                            .thumbnail(0.1f)
                            .placeholder(R.mipmap.ic_banner_default)
                            .error(R.mipmap.ic_banner_default)
                            .into(holder.imageView)
                }
            }
        }


        class ImageHolder(view: View) : RecyclerView.ViewHolder(view) {
            var imageView: ImageView

            init {
                imageView = view as ImageView
            }
        }

    }


}